    # -*- encoding: utf-8 -*-
##############################################################################
#
#    OpenERP, Open Source Management Solution
#    Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>). All Rights Reserved
#    $Id$
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
import time
import netsvc

from osv import fields, osv

from tools.misc import currency
from tools.translate import _
import pooler

from tools import config


class kdvn_payment_term_line(osv.osv):
    _name = "kdvn.payment.term.line"
    _description = "KDVN Payment Term Line"
    #_inherit="kdvn.payment.term.line"

    def search(self, cr, user, args, offset=0, limit=None, order=None,  context=None, count=False):
        if context:
            if 'contract_id' in context.keys():
                cr.execute("Select \
                                id \
                            from \
                                kdvn_payment_term_line\
                            where \
                                contract_id=%s" % context['contract_id'])
                res = cr.fetchall()
                res1=[]
                for tmp in res:
                    res1.append(tmp[0])
                var_filter=res1
                args.append(('id','in',var_filter))
    #                return var_filter
                context=None
            #raise osv.except_osv(_('Invalid action !'),_('Cannot delete Request(s) which are in (%s) State1!' %args))

       # args.append
        return super(kdvn_payment_term_line,self).search(cr, user, args, offset, limit, order=order,context=context, count= count)

    def _new_seq(self, cr, uid, context={}):
        a=1
        if context:
            if 'contract_id' in context:
                payment_line_ids=self.search(cr,uid,[('contract_id','=',context['contract_id'])])
                payments=self.read(cr,uid,payment_line_ids,['sequence'],context)
                a=0
                for sq in payments:
                    if sq['sequence']>a:
                        a=sq['sequence']
                a=a+5
        return a

    def name_get(self, cr, uid, ids, context={}): # Return name + " - " + type
        if not len(ids):
            return []
        reads = self.read(cr, uid, ids, ['name', 'type'], context)
        res = []
        for record in reads:
            payment_term_type=self.fields_get(cr,uid,fields='type')
            name = dict(payment_term_type['type']['selection'])[record['type']]            
            if record['name'] and name:
                name = record['name'] + ' - ' + name
            res.append((record['id'], name))
        return res
    _columns = {
        'name': fields.char('Description', size=100, required=True),
        'sequence': fields.integer('Sequence', required=True, help="The sequence field is used to order the payment term lines from the lowest sequences to the higher ones"),
        'type':fields.selection([('adv','Advance Payment'),('p','Progress'),('re','Retention')],'Type',required=True),
        'value': fields.selection([('percent', 'Percent')], 'Value',required=True),#('fixed', 'Fixed Amount')
        'value_amount':fields.float('Percentage', help="For Value percent enter % ratio between 0-1."),
        'due_date':fields.date('Due date'),        
        'contract_id':fields.many2one('kdvn.contract.client','Contract To Client')
    }
    _defaults = {
        'value': lambda *a: 'percent',
        'sequence':_new_seq,# lambda *a: 5,
        'type':lambda *x:'p'
    }
    _order = "sequence"
kdvn_payment_term_line()
